package com.ushine.web.base.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ushine.web.base.model.relation.UserAndRoleDO;
import com.ushine.web.base.model.relation.UserAndUserGroupDO;
import com.ushine.web.base.model.system.FunctionPermissionDO;
import com.ushine.web.base.model.system.UserDO;
import com.ushine.web.base.service.IUserAndRoleService;
import com.ushine.web.base.service.IUserAndUserGroupService;
import com.ushine.web.base.service.IUserService;
import com.ushine.web.base.facade.IUserRolePermissionFacade;
import com.ushine.web.component.exception.ServiceException;
import com.ushine.web.component.http.HttpResponseVO;
import com.ushine.web.component.page.PageRequestQuery;
import com.ushine.web.component.page.PageResultVO;
import com.ushine.web.log.annotation.SystemControllerLog;
import com.ushine.web.log.constant.LogConstant;
import com.ushine.web.base.view.LoginBeanBO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * @Author: yls
 * @Date: 2021/3/12 13:27
 * @Description: 用户管理
 * @Version 1.0
 */
@RestController
@RequestMapping("system/user")
@Api(tags = "基础模块-用户管理")
@Validated
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserAndRoleService userRoleService;

    @Resource
    private IUserAndUserGroupService userAndUserGroupService;

    @Resource
    private IUserRolePermissionFacade userRolePermissionFacade;

    @SystemControllerLog(operation = LogConstant.CREATE)
    @ApiOperation(value = "添加用户")
    @PostMapping("insertUser")
    public HttpResponseVO<Object> insertUser(@Validated @ApiParam(value = "用户实体", required = true) @RequestBody UserDO user) throws ServiceException {
        UserDO userByUserName = userService.getUserBaseInfo(user.getUsername());
        if (userByUserName != null) {
            return new HttpResponseVO<>().error("添加失败，用户名已存在！");
        }
        Boolean flag = userService.insertUser(user);
        if (Boolean.TRUE.equals(flag)) {
            return new HttpResponseVO<>().ok("操作成功！");
        } else {
            return new HttpResponseVO<>().error("操作失败！");
        }
    }

    @SystemControllerLog(operation = LogConstant.DELETE)
    @ApiOperation(value = "删除用户", notes = "根据id批量删除")
    @DeleteMapping("deleteBatchUsers")
    public HttpResponseVO<Object> deleteBatchUsers(@ApiParam(value = "待删除的用户集合", required = true) @RequestBody List<String> userIds) {
        Boolean flag = userService.deleteUsers(userIds);
        if (Boolean.TRUE.equals(flag)) {
            return new HttpResponseVO<>().ok("删除成功！");
        } else {
            return new HttpResponseVO<>().error("删除失败！");
        }

    }

    @SystemControllerLog(operation = LogConstant.UPDATE)
    @ApiOperation(value = "修改用户", notes = "根据id修改用户的其他属性")
    @PutMapping("updateUser")
    public HttpResponseVO<Object> updateUser(@ApiParam(value = "待修改的用户", required = true) @RequestBody UserDO user) {
        UserDO userByUserName = userService.getUserBaseInfo(user.getUsername());
        if (userByUserName != null && user.getId() > 0 && !user.getId().equals(userByUserName.getId())) {
            return new HttpResponseVO<String>().error("修改失败，用户名已存在！");
        }
        Boolean flag = userService.updateUser(user);
        if (Boolean.TRUE.equals(flag)) {
            return new HttpResponseVO<>().ok("修改成功！");
        } else {
            return new HttpResponseVO<>().error("修改失败");
        }
    }

    @SystemControllerLog(operation = LogConstant.READ)
    @ApiOperation(value = "分页查询")
    @PostMapping("listUserByPage")
    public HttpResponseVO<PageResultVO<UserDO>> listUserByPage(@ApiParam(value = "查询用户条件", required = true) @RequestBody PageRequestQuery<UserDO> pageRequestQuery) {
        Page<UserDO> userPage = userService.listUsersByPage(pageRequestQuery);
        HttpResponseVO<PageResultVO<UserDO>> responseVO = new HttpResponseVO<>();
        return responseVO.ok("查询成功！", userPage);
    }

    @SystemControllerLog(operation = LogConstant.READ)
    @ApiOperation(value = "查询用户（不包括角色、用户组）", notes = "根据用户名查询用户")
    @PostMapping("getUserByUserName")
    public HttpResponseVO<UserDO> getUserByUserName(@ApiParam(value = "用户名", required = true) @RequestParam String userName) {
        UserDO userDO = userService.getUserBaseInfo(userName);
        return new HttpResponseVO<UserDO>().ok("", userDO);
    }

    @SystemControllerLog(operation = LogConstant.READ)
    @ApiOperation(value = "查询用户（包括角色、用户组）", notes = "根据用户名查询用户")
    @PostMapping("getUserRoleAndGroup")
    public HttpResponseVO<UserDO> getUserRoleAndGroup(@ApiParam(value = "用户名", required = true) @RequestParam String userName) throws ServiceException {
        UserDO userDO = userRolePermissionFacade.getUserRoleAndGroup(userName);
        return new HttpResponseVO<UserDO>().ok("", userDO);
    }

    @SystemControllerLog(operation = LogConstant.UPDATE)
    @ApiOperation(value = "修改密码", notes = "修改用户的密码")
    @PostMapping("updatePassword")
    public HttpResponseVO<Object> updatePassword(@ApiParam(value = "用户信息", required = true) @RequestBody LoginBeanBO loginBeanBO) throws ServiceException {
        String username = loginBeanBO.getUsername();
        UserDO userDO = new UserDO();
        userDO.setUsername(username);
        userService.updatePassword(userDO, loginBeanBO.getNewPassword());
        return new HttpResponseVO<>().ok("密码修改成功，请注销当前用户，重新登录！！！");
    }

    @SystemControllerLog(operation = LogConstant.READ)
    @ApiOperation(value = "查询用户权限")
    @PostMapping("listUserPermission")
    public HttpResponseVO<UserDO> listUserRoles(@ApiParam(value = "用户id", required = true) @RequestParam Long userId) throws ServiceException {
        UserDO user = userRolePermissionFacade.listUserAllPermissions(userId);
        List<FunctionPermissionDO> permissions = user.getFunctionPermissions();
        permissions = Optional.ofNullable(permissions).orElse(new ArrayList<>(0));
        List<FunctionPermissionDO> functionPermissionDOList = new ArrayList<>(permissions);
        functionPermissionDOList.sort(Comparator.comparing(FunctionPermissionDO::getOrderNum));
        user.setFunctionPermissions(functionPermissionDOList);
        return new HttpResponseVO<UserDO>().ok("查询用户权限成功！", user);
    }

    @SystemControllerLog(operation = LogConstant.READ)
    @ApiOperation(value = "查询用户权限(树形)")
    @PostMapping("getUserPermissionTree")
    public HttpResponseVO<List<FunctionPermissionDO>> getUserPermissionTree(@ApiParam(value = "用户id", required = true) @RequestParam Long userId) throws ServiceException {
        List<FunctionPermissionDO> permissions = userRolePermissionFacade.listUserPermissionsTree(userId);
        List<FunctionPermissionDO> functionPermissionDOList = new ArrayList<>(permissions);
        functionPermissionDOList.sort(Comparator.comparing(FunctionPermissionDO::getOrderNum));
        return new HttpResponseVO<List<FunctionPermissionDO>>().ok("查询用户权限成功！", functionPermissionDOList);
    }


    @SystemControllerLog(operation = LogConstant.UPDATE)
    @ApiOperation(value = "设置用户角色", notes = "目前支持多个角色设置")
    @PostMapping("setUserRole")
    public HttpResponseVO<Object> setUserRole(@ApiParam(value = "用户角色关联对象", required = true) @RequestBody List<UserAndRoleDO> userRoles) {
        Boolean flag = userRoleService.insertUserRoles(userRoles);
        if (Boolean.TRUE.equals(flag)) {
            return new HttpResponseVO<>().ok("设置用户角色成功！");
        } else {
            return new HttpResponseVO<>().error("设置用户角色失败！");
        }
    }

    @SystemControllerLog(operation = LogConstant.UPDATE)
    @ApiOperation(value = "设置用户所属用户组", notes = "目前支持多个用户组设置")
    @PostMapping("setUserGroup")
    public HttpResponseVO<Object> setUserGroup(@ApiParam(value = "用户和用户组关联对象", required = true) @RequestBody List<UserAndUserGroupDO> userAndUserGroups) {
        Boolean flag = userAndUserGroupService.insertBatchUserAndUserGroups(userAndUserGroups);
        if (Boolean.TRUE.equals(flag)) {
            return new HttpResponseVO<>().ok("设置用户所属用户组！");
        } else {
            return new HttpResponseVO<>().error("设置用户所属用户组！");
        }
    }

}
